package org.dualr.litelog.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.dualr.litelog.dao.CategoryDao;
import org.dualr.litelog.dao.CommentDao;
import org.dualr.litelog.dao.LinkDao;
import org.dualr.litelog.dao.PhotoDao;
import org.dualr.litelog.dao.PostDao;
import org.dualr.litelog.dao.TagDao;
import org.dualr.litelog.entity.Category;
import org.dualr.litelog.entity.Comment;
import org.dualr.litelog.entity.Link;
import org.dualr.litelog.entity.Page;
import org.dualr.litelog.entity.Photo;
import org.dualr.litelog.entity.Post;
import org.dualr.litelog.entity.Tag;
import org.dualr.litelog.utils.LiteLogUtil;
import org.wei.rssreader.RssDAO;
import org.wei.rssreader.RssSourceBO;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Text;

/* 这是一个涉及lp所有管理的servlet，文章的增、删、改；评论的删除；
 * 分类添加，编辑，删除；tag的添加编辑删除使用这个servlet必须是以管
 * 理员的身份登陆后台
 * 这个servlet写的有点python的路由转发器，将就这用吧！！
 * */
@SuppressWarnings("serial")
public class AdminServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// type表示管理类别-文章article，类别category，链接link，评论comment，图片photo
		String entity = req.getParameter("entity");
		// option表示针对管理类别的操作，如：增，删，查，改等
		String option = req.getParameter("option");
		// 路径
		String path = null;
		// 实体id
		Long id = null;
		// type == null
		if (entity == null || "".equals(entity)) {
			resp.sendRedirect("admin/index.jsp");
			return;
		}

		
		//weisong. RSS订阅的玩意，
		if (entity.equals("rsssource")) {
			path = "admin/rssSource.jsp";
			if (option.equals("list")) {
				try {
					//List<RssSourceBO> list = RssDAO.getAll();
					//req.setAttribute("list", list);
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
			if (option.equals("add")) {
				try {
					RssSourceBO bo = new RssSourceBO();
					bo.setUrl(req.getParameter("rss_url"));
					RssDAO.insert(bo);
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		
		
		// 对category的相关操作
		if (entity.equals("category")) {
			path = "admin/category.jsp";
			// 类别管理列表
			if (option.equals("list")) {
				List<Category> categoryList = CategoryDao.getInstance()
						.getAll();
				req.setAttribute("categoryList", categoryList);
				try {
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
			// 添加一个类别
			if (option.equals("add")) {
				if (req.getMethod().equals("POST")) {
					String name = req.getParameter("name");
					String type = req.getParameter("type");
					Long parentId = Long.parseLong(req.getParameter("parentId"));
					Category category = new Category(name, type, parentId);
					CategoryDao.getInstance().insert(category);
					resp.sendRedirect(path);
				}
			}
			
			// 更新类别
			if (option.equals("update")) {
				id = Long.parseLong(req.getParameter("id"));
				String name = req.getParameter("name");
				String type = req.getParameter("type");
				int counts = Integer.parseInt(req.getParameter("counts"));
				Long parentId = Long.parseLong(req.getParameter("parentId"));
				if (id == null || id == 0) {
					resp.sendRedirect("admin?entity=category&option=list");
					return;
				}
				Category category = new Category(id, name, type, parentId, counts);
				CategoryDao.getInstance().updateCategory(category);
				// req.setAttribute("entityId", entityId);
				resp.sendRedirect(path);
			}
			// 删除类别，删除是判断该类别的文章是否为空，否则不允许删除
			if (option.equals("delete")) {
				id = Long.parseLong(req.getParameter("id"));
				// boolean isFlag = false;
				CategoryDao.getInstance().deleteById(id);
				resp.sendRedirect(path);
			}

		}
		
		// 对link的相关操作，有点类似category
		if (entity.equals("link")) {
			// 添加link
			path = "/admin/link.jsp";
			if (option.equals("add") && req.getMethod().equals("POST")) {
				String name = req.getParameter("name");
				String url = req.getParameter("url");
				String title = req.getParameter("title");
				String image = req.getParameter("image");
				Long categoryId = Long.parseLong(req.getParameter("categoryId"));
				Link link = new Link(name, url, title, image, categoryId);
				LinkDao.getInstance().insert(link);
				//category counts ++
				CategoryDao.getInstance().updateCounts(categoryId, "increment");
				resp.sendRedirect(path);
			}
			// 删除link
			if (option.equals("delete")) {
				id = Long.parseLong(req.getParameter("id"));
				LinkDao.getInstance().deleteById(id);
				//category counts --
				Long categoryId = Long.parseLong(req.getParameter("categoryId"));
				CategoryDao.getInstance().updateCounts(categoryId, "decrease");
				resp.sendRedirect(path);
			}
			// 编辑link
			if (option.equals("update")) {
				if (req.getMethod().equals("POST")) {
					id = Long.parseLong(req.getParameter("id"));
					String name = req.getParameter("name");
					String url = req.getParameter("url");
					String title = req.getParameter("title");
					String image = req.getParameter("image");
					Long categoryId = Long.parseLong(req.getParameter("categoryId"));
					Link link = new Link(id, name, url, title, image, categoryId);
					LinkDao.getInstance().update(link);
				}
				resp.sendRedirect(path);
			}
		}
		
		// 添加，编辑，修改，删除文章
		if (entity.equals("post")) {
			// 添加文章
			if (option.equals("add")) {
				if (req.getMethod().equals("POST")) {
					String title = req.getParameter("title");
					Long categoryId = Long.parseLong(req.getParameter("categoryId"));
					String tag = req.getParameter("tag");
					Text description = new Text(req.getParameter("decription"));
					String image = req.getParameter("image");
					Text content = new Text(req.getParameter("content"));
					String status = req.getParameter("status");
					String commentStatus = req.getParameter("commentStatus");
					Date date = new Date();
					String author = LiteLogUtil.getInstance().getPropsValue("/litelog.properties","litelog.author");
					//category counts --
					CategoryDao.getInstance().updateCounts(categoryId, "increment");
					// update tag,count++
					Long tagId = TagDao.getInstance().checkTag(tag);
					if (tagId == 0) {
						Tag oTag = new Tag(tag, 1);
						TagDao.getInstance().insert(oTag);
					} else {
						TagDao.getInstance().updateTagCount(tagId, "increment");
					}
					Post post = new Post(title, categoryId, tag, description, content, image, date, status,commentStatus,author, 0, 0);
					PostDao.getInstance().insert(post);
					try {
						req.getRequestDispatcher(
								"admin?entity=post&option=list").forward(req,
								resp);
					} catch (ServletException e) {
						e.printStackTrace();
					}
				}

			}
			// 获取全部文章
			if (option.equals("list")) {
				int hits;
				hits = PostDao.getInstance().getCountByPropertyStatus("all", "","");
				path = "/admin/posts.jsp";
				int curPage = 1;
				if (req.getParameter("page") != null
						&& !"".equals(req.getParameter("page"))) {
					curPage = Integer.parseInt(req.getParameter("page"));
				}
				int pageSize = Integer.parseInt(LiteLogUtil.getInstance()
						.getPropsValue("/litelog.properties", "litelog.adminPageSize"));
				Page page = LiteLogUtil.getInstance().pager(hits, pageSize,
						curPage);
				int indexStart = (curPage - 1) * pageSize;
				int indexEnd = curPage * pageSize;
				List<Post> postList = PostDao.getInstance().getPostByRange(indexStart, indexEnd);
				req.setAttribute("PostList", postList);
				req.setAttribute("Page", page);
				try {
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}

			// 删除文章
			if (option.equals("delete")) {
				id = Long.parseLong(req.getParameter("id"));
				PostDao.getInstance().deleteById(id);
				//category counts --
				Long categoryId = Long.parseLong(req.getParameter("categoryId"));
				CategoryDao.getInstance().updateCounts(categoryId, "decrease");
				resp.sendRedirect("admin?entity=post&option=list");
			}
			// 修改文章
			if (option.equals("edit")) {	
				if (req.getMethod().equals("POST")) {
					id = Long.parseLong(req.getParameter("id"));
					String title = req.getParameter("title");
					Long categoryId = Long.parseLong(req.getParameter("categoryId"));
					Text description = new Text(req.getParameter("decription"));
					String image = req.getParameter("image");
					Text content = new Text(req.getParameter("content"));
					String status = req.getParameter("status");
					String commentStatus = req.getParameter("commentStatus");
					// Date date = new Date();
					Post post = new Post(id, title, categoryId, description, content,image,status,commentStatus);
					PostDao.getInstance().update(post);
					resp.sendRedirect("admin?entity=post&option=list");
				}
			}
			// 获取文章详情
			if (option.equals("detail")) {
				path = "/admin/detail.jsp";
				id = Long.parseLong(req.getParameter("id"));
				Post post = PostDao.getInstance().getById(id);
				req.setAttribute("Post", post);
				List<Comment> comment = CommentDao.getInstance().getCommentByPostId(id);
				req.setAttribute("Comment", comment);
				try {
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
		}
		
		// 管理评论，主要是删除评论
		if (entity.equals("comment")) {
			if (option.equals("list")) {
				int hits;
				hits = CommentDao.getInstance().getCount();
				path = "/admin/comment.jsp";
				int curPage = 1;
				if (req.getParameter("page") != null
						&& !"".equals(req.getParameter("page"))) {
					curPage = Integer.parseInt(req.getParameter("page"));
				}
				int pageSize = Integer.parseInt(LiteLogUtil.getInstance().getPropsValue("/litelog.properties", "litelog.adminPageSize"));
				Page page = LiteLogUtil.getInstance().pager(hits, pageSize,
						curPage);
				int indexStart = (curPage - 1) * pageSize;
				int indexEnd = curPage * pageSize;
				List<Comment> commentList = CommentDao.getInstance().getCommentByRange(indexStart, indexEnd);
				req.setAttribute("commentList", commentList);
				req.setAttribute("Page", page);
				try {
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
			// 删除评论
			if (option.equals("delete")) {
				id = Long.parseLong(req.getParameter("id"));
				Long postId = Long.parseLong(req.getParameter("postId"));
				PostDao.getInstance().updateHitsorCommentCount(postId, "commentCount", "decrease ");
				CommentDao.getInstance().deleteById(id);
				resp.sendRedirect("admin?entity=comment&option=list");
			}
		}

		
		
		// photo
		if (entity.equals("photo")) {
			// 图片列表
			if (option.equals("list")) {
				int hits;
				hits = PhotoDao.getInstance().getCount();
				path = "/admin/photo.jsp";
				int curPage = 1;
				if (req.getParameter("page") != null
						&& !"".equals(req.getParameter("page"))) {
					curPage = Integer.parseInt(req.getParameter("page"));
				}
				int pageSize = Integer.parseInt(LiteLogUtil.getInstance()
						.getPropsValue("/litelog.properties", "litelog.adminPageSize"));
				Page page = LiteLogUtil.getInstance().pager(hits, pageSize,
						curPage);
				int indexStart = (curPage - 1) * pageSize;
				int indexEnd = curPage * pageSize;
				List<Object[]> photoList = PhotoDao.getInstance().getAllByPage(
						indexStart, indexEnd);
				req.setAttribute("photoList", photoList);
				req.setAttribute("Page", page);
				try {
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}

			// 上传
			if (option.equals("upload")) {
				ServletFileUpload upload = new ServletFileUpload();
				FileItemIterator iterator = null;
				try {
					iterator = upload.getItemIterator(req);
				} catch (FileUploadException e) {
					e.printStackTrace();
				}
				try {
					while (iterator.hasNext()) {
						FileItemStream item = iterator.next();
						InputStream stream = item.openStream();
						if (item.isFormField()) {
							// Handle form field
						} else {
							// Handle the uploaded file
							Blob bImg = new Blob(IOUtils.toByteArray(stream));
							Date date = new Date();
							String name = item.getName();
							Photo photo = new Photo(name, date, bImg);
							PhotoDao.getInstance().insert(photo);
							resp.sendRedirect("admin?entity=photo&option=list");
						}

					}
				} catch (FileUploadException e) {
					e.printStackTrace();
				}

			}
			// edit
			if (option.equals("edit")) {
				id = Long.parseLong(req.getParameter("id"));
				if (id == 0 || id == null) {
					resp.sendRedirect("admin?entity=photo&option=list");
				}
				if (req.getMethod().equals("GET")) {
					Photo photo = null;
					photo = PhotoDao.getInstance().getById(id);
					req.setAttribute("photo", photo);
					try {
						req.getRequestDispatcher("/admin/photoEdit.jsp")
								.forward(req, resp);
					} catch (ServletException e) {
						e.printStackTrace();
					}
				} else {
					String name = req.getParameter("name");
					String description = req.getParameter("description");
					Long categoryId = Long.parseLong(req.getParameter("categoryId"));
					Photo photo = new Photo(id, name, categoryId, description);
					PhotoDao.getInstance().update(photo);
					resp.sendRedirect("admin?entity=photo&option=list");
				}
			}
			// delete
			if (option.equals("delete")) {
				id = Long.parseLong(req.getParameter("id"));
				PhotoDao.getInstance().deleteById(id);
				//category counts --
				Long categoryId = Long.parseLong(req.getParameter("categoryId"));
				CategoryDao.getInstance().updateCounts(categoryId, "decrease");
				resp.sendRedirect("admin?entity=photo&option=list");
			}

		}
	}
}
